package com.linkage.jz.bankruptcy.activity.Vote;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteRule;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * 新建表决规则
 */
public class ProVoteNewRuleActivity extends BaseActivity implements View.OnClickListener {

    private String mProjectId;
    private List<ProVoteRule> mRuleList = new ArrayList<>();
    private ProVoteRule mRule = new ProVoteRule();

    private TextView tv_vote_rule_type;
    private EditText et_vote_rule_percent_person, et_vote_rule_percent_money, et_vote_rule_name, et_vote_rule_explains;


    @Override
    public void initData() {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {

    }

    @Override
    public void initView() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_pro_vote_new_rule);
        super.onCreate(savedInstanceState);
        titlebar_title.setText("自定义规则");

        mProjectId = getIntent().getStringExtra(KEY_PROJECTID);
        mRule.setType(-1);

        initViews();
        titlebar_menu_text.setOnClickListener(this);
        getRuleList();
    }

    private void initViews() {
        titlebar_menu_text.setVisibility(View.VISIBLE);

        tv_vote_rule_type = findViewById(R.id.tv_vote_rule_type);
        et_vote_rule_percent_person = findViewById(R.id.et_vote_rule_percent_person);
        et_vote_rule_percent_money = findViewById(R.id.et_vote_rule_percent_money);
        et_vote_rule_name = findViewById(R.id.et_vote_rule_name);
        et_vote_rule_explains = findViewById(R.id.et_vote_rule_explains);


        findViewById(R.id.btn_vote_rule_percent_person_minus).setOnClickListener(this);
        findViewById(R.id.btn_vote_rule_percent_person_add).setOnClickListener(this);
        findViewById(R.id.btn_vote_rule_percent_money_minus).setOnClickListener(this);
        findViewById(R.id.btn_vote_rule_percent_money_add).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String personstr = et_vote_rule_percent_person.getText().toString().trim();
        String moneystr = et_vote_rule_percent_money.getText().toString().trim();
        double value_person = 0;
        double value_money = 0;

        try {
            value_person = Double.parseDouble(personstr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            value_money = Double.parseDouble(moneystr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        switch (v.getId()) {
            case R.id.tv_vote_rule_type:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请选择表决规则");
                if (mRuleList.size() == 0) {
                    ToastUtil.showShort("无表决规则可选项");
                    return;
                }

                final String[] strRules = new String[mRuleList.size()];
                for (int i = 0; i < mRuleList.size(); i++) {
                    strRules[i] = mRuleList.get(i).getName();
                }
                builder.setItems(strRules, (dialog, which) -> {
                    mRule.setGrouped(mRuleList.get(which).getGrouped());
                    mRule.setType(mRuleList.get(which).getType());
                    tv_vote_rule_type.setText(mRuleList.get(which).getName());
                    et_vote_rule_name.setText(mRuleList.get(which).getName());
                    et_vote_rule_percent_person.setText(String.valueOf(mRuleList.get(which).getPersonnelPercent()));
                    et_vote_rule_percent_money.setText(String.valueOf(mRuleList.get(which).getMoneyPercent()));
                    et_vote_rule_explains.setText(mRuleList.get(which).getExplains());
                });
                builder.show();
                break;
            case R.id.btn_vote_rule_percent_person_minus:
                if (value_person >= 1) {
                    value_person = value_person - 1;
                }
                et_vote_rule_percent_person.setText(String.valueOf(value_person));
                break;
            case R.id.btn_vote_rule_percent_person_add:
                if (value_person <= 99) {
                    value_person = value_person + 1;
                }
                et_vote_rule_percent_person.setText(String.valueOf(value_person));
                break;
            case R.id.btn_vote_rule_percent_money_minus:
                if (value_money >= 1) {
                    value_money = value_money - 1;
                }
                et_vote_rule_percent_money.setText(String.valueOf(value_money));
                break;
            case R.id.btn_vote_rule_percent_money_add:
                if (value_money <= 99) {
                    value_money = value_money + 1;
                }
                et_vote_rule_percent_money.setText(String.valueOf(value_money));
                break;
            case R.id.titlebar_menu_text:
                saveData();
                break;

        }
    }

    private void getRuleList() {
        Network
                .getAPIService()
                .getVoteRuleList(getUserToken(), "null")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonArray arr = json.getAsJsonArray("data");
                        List<ProVoteRule> list = ProVoteRule.parse(arr);
                        mRuleList.clear();
                        mRuleList.addAll(list);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }

    private void saveData() {
        String rule_name = et_vote_rule_name.getText().toString().trim();
        String rule_desc = et_vote_rule_explains.getText().toString().trim();
        String personstr = et_vote_rule_percent_person.getText().toString().trim();
        String moneystr = et_vote_rule_percent_money.getText().toString().trim();
        double value_person = 0;
        double value_money = 0;

        if (mRule.getType() == -1) {
            ToastUtil.showShort("请选择表决规则");
            return;
        }
        if (TextUtils.isEmpty(rule_name)) {
            ToastUtil.showShort("规则名称不能为空");
            return;
        }

        boolean chongfu = false;
        for (int i = 0; i < mRuleList.size(); i++) {
            if (TextUtils.equals(rule_name, mRuleList.get(i).getName())) {
                chongfu = true;
            }
        }
        if (chongfu) {
            ToastUtil.showShort("规则名称不能重复");
            return;
        }

        if (TextUtils.isEmpty(personstr)) {
            ToastUtil.showShort("同意人数占比不能为空");
            return;
        }

        if (TextUtils.isEmpty(moneystr)) {
            ToastUtil.showShort("同意金额占比不能为空");
            return;
        }
        try {
            value_person = Double.parseDouble(personstr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            value_money = Double.parseDouble(moneystr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mRule.setName(rule_name);
        mRule.setExplains(rule_desc);
        mRule.setPersonnelPercent(value_person);
        mRule.setMoneyPercent(value_money);

        showLoading("提交中...");
        Network
                .getAPIService()
                .addVoteRule(getUserToken(), mProjectId, rule_name, rule_desc, value_money, value_person,
                        mRule.getType())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }

                        Intent intent = new Intent();
                        intent.putExtra("rule", mRule);
                        setResult(RESULT_OK, intent);

                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }
}
